package com.david.cloud.filter;

import com.google.common.util.concurrent.RateLimiter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
//@Configuration
@EnableConfigurationProperties(RateLimiterProperties.class)
public class RateLimiterConfig {
    @Autowired
    private RateLimiterProperties properties;

    //用户ip限流
    @Bean
    @Scope("prototype")
    public RateLimiter ratelimiter() {
        Double permitsPerSecond = (double) properties.getPermits() / (double) (properties.getPeriod() * 60);
        RateLimiter rateLimiter = RateLimiter.create(permitsPerSecond);
        return rateLimiter;
    }


    @SneakyThrows
    @PostConstruct
    public void report() {
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> {
            log.info("permits:{}, period:{}", properties.getPermits(), properties.getPeriod());
        }, 10, 10, TimeUnit.SECONDS);
    }

}
